package com.suitsoft.bdms.commos;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;


/**
 * 模拟登陆
 * 获取登陆成功页面的指定字符
 */
public class HttpPostLogin {
	
	private final String SIGNS = "$)^^)(%)*";

    // The HttpClient is used in one session
    private HttpResponse response;
    private DefaultHttpClient httpclient = new DefaultHttpClient();
    
    private String loginUrl;
    private String sourceHtml="";
    private Map<String,String> userPass;
    private CookieStore cookieStore;
    
    public HttpPostLogin(String loginUrl,Map<String,String> userPwd) {
    	this.userPass = userPwd;
		this.loginUrl = loginUrl;
	}
    
    
    public HttpPostLogin() {
	}

	public void init(String loginUrl,Map<String,String> userPwd) {
    	this.userPass = userPwd;
		this.loginUrl = loginUrl;
	}


	private boolean login() {
        HttpPost httpost = new HttpPost(loginUrl);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        
        // 创建一个本地Cookie存储的实例
		cookieStore =  new BasicCookieStore();
		//创建一个本地上下文信息
		HttpContext localContext = new BasicHttpContext();
		//在本地上下问中绑定一个本地存储
//		localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        
        for(Map.Entry<String, String> m : userPass.entrySet()){
        	nvps.add(new BasicNameValuePair(m.getKey(), m.getValue()));
        }
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps));
            response = httpclient.execute(httpost,localContext);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            httpost.abort();
        }
        return true;
    }
	

    private String getRedirectLocation() {
        Header locationHeader = response.getFirstHeader("Location");
        if (locationHeader == null) {
            return null;
        }
        return locationHeader.getValue();
    }
    
    public Header[] getAllHeader(){
    	return response.getAllHeaders();
    }
    
    public List<Cookie> getAllCookie(){
    	return cookieStore.getCookies();
    }

    private String getText(String redirectLocation) {
        HttpGet httpget = new HttpGet(redirectLocation);
        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = "";
        try {
            responseBody = httpclient.execute(httpget, responseHandler);
        } catch (Exception e) {
            e.printStackTrace();
            responseBody = null;
        } finally {
            httpget.abort();
//            httpclient.getConnectionManager().shutdown();
        }
        return responseBody;
    }

    public void printText() {
        if (login()) {
            String redirectLocation = getRedirectLocation();
            System.out.println(redirectLocation);
            if (redirectLocation != null) {
            	sourceHtml = getText(redirectLocation);
            	System.out.println(sourceHtml);
            }
        }
    }
    
    /**
     * 判断是否登陆成功
     * <pre>就是判断返回的源码中是否存在特定字符</pre>
     * @param url
     * @param userName
     * @param password
     * @return
     */
    public boolean isLoginSuccess(){
    	printText();
    	if(sourceHtml.indexOf(SIGNS) != -1){
    		return true;
    	}else{
    		return false;
    	}
    }

	public HttpResponse getResponse(){
    	return response; 
    }

    public static void main(String[] args) {
    	Map<String,String> m = new HashMap<String,String>();
//    	m.put("loginName", "11201212");
//    	m.put("password", "11201212");
//        HttpPostLogin renRen = new HttpPostLogin("http://125.223.113.127:8080/WAS/system/systemAction_novalidlogin.action",m);
    	m.put("j_username", "admin");
    	m.put("j_password", "admin");
        HttpPostLogin renRen = new HttpPostLogin("http://125.223.113.125:8080/ut/j_spring_security_check",m);
        System.out.println(renRen.isLoginSuccess());
        Header[] headers = renRen.getAllHeader();
		for (int i = 0; i<headers.length; i++) {
		    if(headers[i].getName().equals("Set-Cookie")){
		    	String s = headers[i].getValue();
		    	s  = s.substring(s.indexOf("="), s.indexOf(";"));
		    	System.out.println("=======" + s);
		    }
		}
    }
//	public static void main(String[] args) throws ClientProtocolException, IOException {
//		HttpPost httpost = new HttpPost("http://125.223.113.125:8080/ut/j_spring_security_check");
//		//获取Cookie的信息
//		HttpClient httpclientme = new DefaultHttpClient();
//		// 创建一个本地Cookie存储的实例
//		CookieStore cookieStore =  new BasicCookieStore();
//		//创建一个本地上下文信息
//		HttpContext localContext = new BasicHttpContext();
//		//在本地上下问中绑定一个本地存储
//		localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//		//传递本地的http上下文给服务器
//		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//		nvps.add(new BasicNameValuePair("j_username", "2009161105"));
//		nvps.add(new BasicNameValuePair("j_password", "123"));
//		httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//		HttpResponse response = httpclientme.execute(httpost, localContext);
//		//获取本地信息
//		HttpEntity entity = response.getEntity();
//		//System.out.println(response.getStatusLine());
//		if (entity != null) {
//		    System.out.println("Response content length: " + entity.getContentLength());
//		}
//
//		//获取cookie中的各种信息
//		List<Cookie> cookies = cookieStore.getCookies();
//		for (int i = 0; i < cookies.size(); i++) {
//		    System.out.println("Local cookie: " + cookies.get(i));
//		}
//		//获取消息头的信息
//		Header[] headers = response.getAllHeaders();
//		for (int i = 0; i<headers.length; i++) {
//		    System.out.println(headers[i]);
//		}
//		
//		
//	}
}